package com.louis.iread.ui;

import android.support.annotation.NonNull;
import android.support.design.bottomnavigation.LabelVisibilityMode;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.louis.iread.R;
import com.louis.iread.bean.Book;
import com.louis.iread.bean.Website;
import com.louis.iread.bean.WebsiteMgr;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.AppUtils;
import com.louis.iread.utils.BottomNavigationViewHelper;
import com.louis.iread.utils.ConstValue;
import com.louis.iread.utils.DbUtil;
import com.umeng.analytics.MobclickAgent;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity{

    private Fragment currentFragment;
    private Map<Integer, Fragment> fragments;
    private Map<Integer, Integer> titles;
    private TextView titleView;
    private List<Integer> positions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SkinMgr.getInstance().register(this);
        setContentView(R.layout.activity_main);

        //实现沉浸式状态栏
        if (Build.VERSION.SDK_INT >= 19) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        AppUtils.init(this);
        initDb();
        initPositions();
        initWebsites();
        initBottomBar();
        initTitles();
        initFragments();
    }

    private void initPositions() {
        positions = new ArrayList<>();
        positions.add(R.string.booksheft);
//        positions.add(R.string.search);
        positions.add(R.string.classify);
        positions.add(R.string.settings);
    }


    /*
    初始化标题数组
     */
    private void initTitles() {
        //标题数组
        titles = new HashMap<>();
        titles.put(R.string.booksheft, R.string.booksheft);
//        titles.put(R.string.search, R.string.search);
//        titles.add(R.string.chart);
        titles.put(R.string.classify, R.string.classify);
        titles.put(R.string.settings, R.string.settings);
        //设置缺省title
        titleView = (TextView) findViewById(R.id.app_title);
        titleView.setText(titles.get(R.string.booksheft));
        titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SkinMgr.getInstance().switchReadMode();
            }
        });
    }


    /*
    初始化fragments
     */
    private void initFragments() {
        //fragment数组
        fragments = new HashMap<>();
        fragments.put(R.string.booksheft, BooksheftFrm.newInstance("booksheft"));
//        fragments.put(R.string.search, SearchActivity.newInstance("search"));
//        fragments.add(ChartFrm.newInstance("chart"));
        fragments.put(R.string.classify, ClassifyFrm.newInstance("classify"));
        fragments.put(R.string.settings, SettingsFrm.newInstance("settings"));

        //设置缺省fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.contentContainer, fragments.get(R.string.booksheft));
        transaction.show(fragments.get(R.string.booksheft));
        transaction.commit();
        currentFragment = fragments.get(R.string.booksheft);
    }

    /*
    初始化底部Tab
     */
    private void initBottomBar() {
        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int position = item.getOrder();
                Log.e("test", "index = " + position);
                FragmentManager fm = getSupportFragmentManager();
                Fragment fragment = fragments.get(positions.get(position));
                if (currentFragment == fragment) {
                    return false;
                }
                FragmentTransaction transaction = fm.beginTransaction();
                if (!fragment.isAdded()) {
                    transaction.add(R.id.contentContainer, fragment);
                }
                transaction.show(fragment);
                transaction.commit();
                titleView.setText(titles.get(positions.get(position)));
                transaction.hide(currentFragment);
                currentFragment = fragment;
                return false;
            }
        });
    }


    //连续按两次返回键退出应用
    private long mExitTime = 0;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    public boolean initWebsites() {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("cfg.json"));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String jsonStr = "";
            while ((line = bufReader.readLine()) != null)
                jsonStr += line;
            List<Website> websites = JSON.parseArray(jsonStr, Website.class);
            WebsiteMgr manager = WebsiteMgr.getManager();
            manager.setWebsites(websites);
            manager.setMainSite(manager.getWebsite("www.80txt.la"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    void initDb() {
        DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                .setDbName("novel.db")
                // 不设置dbDir时, 默认存储在app的私有目录.
                //.setDbDir(getApplicationContext().getFilesDir()) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
                .setDbVersion(ConstValue.DB_VERSION_2)
                .setAllowTransaction(true)
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        if (oldVersion == ConstValue.DB_VERSION_1) {
                            try {
                                db.addColumn(Book.class, "state");
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                        // TODO: ...
                        // db.addColumn(...);
                        // db.dropTable(...);
                        // ...
                        // or
                        // db.dropDb();
                    }
                });
        DbUtil.init(daoConfig);
    }
    private static final String TAG = "MainActivity";

    //退出当前Activity时被调用,调用之后Activity就结束了
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkinMgr.getInstance().unregister(this);
        Log.i(TAG, "onDestory called.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
